package com.ss.android.auto.launch.tasks.collector.stage1

import android.os.Build
import android.view.View
import android.webkit.CookieManager
import com.bytedance.common.utility.concurrent.ThreadPlus
import com.bytedance.dataplatform.abTest.Experiments
import com.dcd.abtest.experiment.launch.HomePageLaunchTaskOptExperiment
import com.ss.android.auto.btmevent.BtmUtil
import com.ss.android.auto.config.settings.SearchSettingsIndex
import com.ss.android.auto.crash.IAutoCrashService
import com.ss.android.auto.homepage_api.IHomepageService
import com.ss.android.auto.init.AppCoreData
import com.ss.android.auto.launch.HeaderTask
import com.ss.android.auto.launch.WorkerMainThreadTask
import com.ss.android.auto.launch.helper.ServiceRegisterInitHelper
import com.ss.android.auto.launch.helper.WebViewGpuCacheDeleteHelper
import com.ss.android.auto.launch.tasks.collector.AsyncThreadTaskCollector
import com.ss.android.auto.launch.tasks.old.WorkerBackGroundTaskNoHeader
import com.ss.android.auto.launch.tasks.old.WorkerBackgroundTaskA
import com.ss.android.auto.lynx.Bullet
import com.ss.android.auto.lynx.prefetch.DefaultPrefetchProcessor
import com.ss.android.auto.mannor.MannorInitializer
import com.ss.android.auto.optimize.serviceapi.IOptimizeService
import com.ss.android.auto.optimize.serviceapi.LaunchOptType
import com.ss.android.auto.optimize.serviceapi.OptimizeServiceKt.Companion.isLaunchOptDecemberEnable
import com.ss.android.auto.servicemanagerwrapper.AutoServiceManager
import com.ss.android.auto.uicomponent.font.TypefaceHelper
import com.ss.android.auto.uicomponent.text.DCDIconFontTextWidget
import com.ss.android.auto.utils.NetworkTypeFetcher
import com.ss.android.auto.x2c.init
import com.ss.android.basicapi.application.BaseAutoApplication
import com.ss.android.common.app.AbsApplication
import com.ss.android.globalcard.simpleitem.FeedCarSeriesNewItemV2
import com.ss.android.globalcard.utils.FrescoInitMonitor
import com.ss.android.image.AutoCacheKeyFactory


/**
 * Application onCreate 开始到结束之间的异步任务，不能依赖Net、Account等核心 SDK
 *
 *  @author zhongxinyuan @ ByteDance Inc
 *  @since   2022/10/20
 */
object Stage1ToStage2AsyncTasks : AsyncThreadTaskCollector() {

    override fun collectSubTasks() {
        addSubTask("initQuicklyTasks") {
            WorkerBackGroundTaskNoHeader.initQuicklyTasks()
        }
        addSubTask("CookieManager") {
            ThreadPlus.submitRunnable {
                val isX2COpen =
                    SearchSettingsIndex.ins(BaseAutoApplication.getApplication()).mAutoX2COpen.value
                init(isX2COpen)
                if (Build.VERSION.SDK_INT < 35) {
                    CookieManager.getInstance()
                }
            }
            FrescoInitMonitor.preTaskRun = true
        }
        if (!HomePageLaunchTaskOptExperiment.open()) {
            addSubTask("initTTOpenSsl") {
                HeaderTask.initTTOpenSsl()
                FrescoInitMonitor.preTaskRun = true
            }
        }
        addSubTask("initFresco") {
            FrescoInitMonitor.initFrescoRunBegin = true
            WorkerBackGroundTaskNoHeader.initFresco()
            val homepageService: IHomepageService? = AutoServiceManager.getService2(IHomepageService::class.java)
            //临时调整开屏View预加载到Fresco初始化之后
            val enablePreloadSplashAdAfterFresco = SearchSettingsIndex.ins(AbsApplication.getApplication()).enablePreloadSplashAdAfterFresco.value
            if (enablePreloadSplashAdAfterFresco) {
                homepageService?.boostSplashView()
            }
            WorkerBackGroundTaskNoHeader.optInitRefreshManager()
            FrescoInitMonitor.initFrescoRunEnd = true
        }

        if (HomePageLaunchTaskOptExperiment.open()) {
            addSubTask("initCert") {
                FrescoInitMonitor.nextTaskRun = true
                WorkerMainThreadTask.initCert() // 认证初始化
            }
            addSubTask("initLynx") {
                HeaderTask.initLynx()
                if (Experiments.getLynxCheckInit(true) == 1) {
                    Bullet.initBulletSdkImmediate()
                    Bullet.initPrefetch(DefaultPrefetchProcessor())
                }
                // mannor依赖lynx初始化，所以改在initLynx()之后同步初始化
                MannorInitializer.ensureInitialized()
            }
        }

        addSubTask("startPreloadViews") {
            FrescoInitMonitor.nextTaskRun = true
            WorkerBackGroundTaskNoHeader.startPreloadViews()
        }
        if (!HomePageLaunchTaskOptExperiment.open()) {
            addSubTask("TypefaceHelper") {
                TypefaceHelper.initialize(AbsApplication.getApplication())
            }
            addSubTask("registerNetReceiver") {
                WorkerBackGroundTaskNoHeader.registerNetReceiver(AbsApplication.getApplication())
            }
            addSubTask("initGlobalCategory") {
                AutoServiceManager.getService2(IHomepageService::class.java)?.initGlobalCategoryThemeParamsManager()
            }
        }
        addSubTask("WebViewGpuCacheDelete") {
            try {
                WebViewGpuCacheDeleteHelper.deleteCache(BaseAutoApplication.getApplication())
            } catch (throwable: Throwable) {
                throwable.printStackTrace()
            }

        }
        addSubTask("DCDIconFontTextWidget") {
            val mOptimizeService =
                AutoServiceManager.getService2(IOptimizeService::class.java)
            if (mOptimizeService != null) {
                if (SearchSettingsIndex.ins(AbsApplication.getApplication()).mFrescoCacheRemoveHost.value) {
                    AutoCacheKeyFactory.optRemoveHostForCache()
                }
                if (!HomePageLaunchTaskOptExperiment.open()) {
                    DCDIconFontTextWidget(BaseAutoApplication.getApplication())
                }
                if (!mOptimizeService.isOpenPreload) {
                    if (isLaunchOptDecemberEnable(LaunchOptType.ASYNC)) {
                        ThreadPlus.submitRunnable {
                            FeedCarSeriesNewItemV2.createHolderStatic(
                                View.inflate(
                                    AbsApplication.getApplication(),
                                    FeedCarSeriesNewItemV2.getLayoutIdStaic(),
                                    null
                                )
                            )
                        }
                    } else {
                        FeedCarSeriesNewItemV2.createHolderStatic(
                            View.inflate(
                                AbsApplication.getApplication(),
                                FeedCarSeriesNewItemV2.getLayoutIdStaic(),
                                null
                            )
                        )
                    }
                }
            }
        }
        if (!HomePageLaunchTaskOptExperiment.open()) {
            addSubTask("initCert") {
                WorkerMainThreadTask.initCert() // 认证初始化
            }
        }
        addSubTask("initHotFix") {
            HeaderTask.initHotFix()
        }
        if (!HomePageLaunchTaskOptExperiment.open()) {
            addSubTask("initLynx") {
                HeaderTask.initLynx()
                if (Experiments.getLynxCheckInit(true) == 1) {
                    Bullet.initBulletSdkImmediate()
                    Bullet.initPrefetch(DefaultPrefetchProcessor())
                }
                // mannor依赖lynx初始化，所以改在initLynx()之后同步初始化
                MannorInitializer.ensureInitialized()
            }
        }
        addSubTask("initBtm") {
            BtmUtil.initBtm(AbsApplication.getApplication())
        }
        if (!HomePageLaunchTaskOptExperiment.open()) {
            addSubTask("NetworkTypeFetcher") {
                // networktype 获取频繁问题
                NetworkTypeFetcher.getInstance().init(AbsApplication.getApplication())
            }
            addSubTask("initStrategySdk") {
                HeaderTask.initStrategySdk()
            }
        }
        addSubTask("initWebViewMonitor") {
            HeaderTask.initWebViewMonitor()
        }
        addSubTask("onCreateAsyncTask") {
            AutoServiceManager.getService2<IAutoCrashService>(IAutoCrashService::class.java)
                ?.onCreateAsyncTask(
                    AbsApplication.getApplication(),
                    AppCoreData.getInstance().isMainProcess,
                    AppCoreData.getInstance().isDebug
                )
        }
        addSubTask("initConstantModule") {
            WorkerBackgroundTaskA.initConstantModule() // Constant模块初始
        }
        addSubTask("ServiceRegisterInit") {
            ServiceRegisterInitHelper.init(AbsApplication.getApplication()) // 模块提供的服务注册
        }
    }

}